package com.imooc.controller;


import com.imooc.pojo.Users;
import com.imooc.pojo.vo.UsersVO;
import com.imooc.service.UserService;
import com.imooc.utils.IMoocJSONResult;
import com.imooc.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author Zhou
 * @create 2020-11-13 12:16
 */
@RestController
@Api(value = "用户注册登录的接口", tags = {"注册和登录的controller"})
public class RegisterLoginController extends BasicController {
    @Autowired
    private UserService userService;

    @ApiOperation(value = "用户注册", notes = "用户注册的接口")
    @Transactional
    @PostMapping("/register")
    public IMoocJSONResult userRegister(@RequestBody Users user) throws Exception {
        //1. 判断用户名和密码不为空
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return IMoocJSONResult.errorMsg("用户名和密码不能为空");
        }
        //2. 判断用户名是否存在
        boolean usernameIsExit = userService.queryUsernameIsExit(user.getUsername());
        if (usernameIsExit) {
            return IMoocJSONResult.errorMsg("用户名已存在");
        } else {
            //3. 保存用户注册信息
            user.setNickname(user.getUsername());
            user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
            user.setFansCounts(0);
            user.setFollowCounts(0);
            user.setReceiveLikeCounts(0);
            userService.saveUser(user);
        }
        user.setPassword(""); //user进行回传时为了密码安全问题我们将password设置为空
        UsersVO userVO = setUserRedisSessionToken(user);
        return IMoocJSONResult.ok(userVO);
    }

    /**
     * 利用redis做无状态Session
     * @param userModel
     * @return
     */
    public UsersVO setUserRedisSessionToken(Users userModel){
        String uniqueToke = UUID.randomUUID().toString();
        redis.set(USER_REDIS_SESSION + ":" + userModel.getId(), uniqueToke, 1000 * 60 * 30);

        UsersVO userVO = new UsersVO();
        BeanUtils.copyProperties(userModel, userVO);
        userVO.setUserToken(uniqueToke);
        return userVO;
    }

    @ApiOperation(value = "用户登录", notes = "用户登录的接口")
    @Transactional
    @PostMapping("/login")
    public IMoocJSONResult userLogin(@RequestBody Users user) throws Exception {
        if (StringUtils.isEmpty(user.getUsername()) && StringUtils.isEmpty(user.getPassword())) {
            return IMoocJSONResult.errorMsg("用户名和密码不能为空");
        }

        //判断用户名是否存在
        Users queryUser = userService.queryUserByUsername(user.getUsername(), MD5Utils.getMD5Str(user.getPassword()));

        if (queryUser != null) {
            //进行密码校验
            queryUser.setPassword("");
            UsersVO userVO = setUserRedisSessionToken(queryUser);
            return IMoocJSONResult.ok(userVO);
        } else {
            if (userService.queryUsernameIsExit(user.getUsername())) {
                return IMoocJSONResult.errorMsg("密码错误，请重新输入");
            }
            return IMoocJSONResult.errorMsg("用户名不存在，请注册");
        }
    }


    @ApiOperation(value = "用户注销", notes = "用户注销的接口")
    @ApiImplicitParam(name = "userId", value = "用户Id", required = true, dataType = "String", paramType = "query")
    @PostMapping("/logout")
    public IMoocJSONResult userLogout(String userId){
        redis.del(USER_REDIS_SESSION + ":" + userId);
        return IMoocJSONResult.ok();
    }
}
